import React, { useState, useEffect } from 'react';
import { Button, Text } from 'packages/ui-shared/src/atoms';
import { useNavigate, useLocation } from 'react-router-dom';
import axios from 'axios';
import SessionIndicator from '../components/SessionIndicator';
import Sidebar from '../components/Sidebar';
import DashboardPage from '../pages/DashboardPage';
import AuditLogPage from '../pages/AuditLogPage';

import ClassroomManagementPage from '../pages/ClassroomManagementPage';
import GradeManagementPage from '../pages/GradeManagementPage';
import TeacherManagementPage from '../pages/TeacherManagementPage';
import ComprehensiveScoreManagementPage from '../pages/ComprehensiveScoreManagementPage';
import SystemSettingsPage from '../pages/SystemSettingsPage';
import PermissionManagementPage from '../pages/PermissionManagementPage';
import ClassManagementPage from '../pages/ClassManagementPage';
import RoleManagementPage from '../pages/RoleManagementPage';
import CounselorManagementPage from '../pages/CounselorManagementPage';
import AttendanceManagementPage from '../pages/AttendanceManagementPage';
import NotificationManagementPage from '../pages/NotificationManagementPage';
import MarketDepartmentManagementPage from '../pages/MarketDepartmentManagementPage';
import CollegeManagementPage from '../pages/CollegeManagementPage';
import StudentManagementPage from '../pages/StudentManagementPage';
import DormitoryManagementPage from '../pages/DormitoryManagementPage';
import DormitoryBuildingManagementPage from '../pages/DormitoryBuildingManagementPage';
import { useSession } from '../hooks/useSession';
import { useTheme, useI18n } from '@dev_deom/ui-shared';

export function App() {
  const navigate = useNavigate();
  const location = useLocation();
  const { setLocal, local } = useI18n();
  const { Theme, setTheme } = useTheme();
  const { isAuthenticated } = useSession();
  
  const handleLang = () => setLocal(local === 'zh' ? 'en' : 'zh');
  const handleTheme = () => setTheme(Theme === 'light' ? 'dark' : 'light');
  
  // 侧边栏状态
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  
  useEffect(() => {
    axios.get('/api/users').then((res) => {
      console.log(res.data.data.list);
    });
  }, []);

  // 登录/注销处理
  const handleLogin = () => {
    navigate('/login');
  };

  // 获取面包屑导航数据
  const getBreadcrumbData = () => {
    const pathname = location.pathname;
    const breadcrumbs = [{ label: '首页', path: '/app' }];
    
    if (pathname === '/app' || pathname === '/app/dashboard') {
      breadcrumbs.push({ label: '工作区', path: '/app/dashboard' });
    } else if (pathname.startsWith('/app/colleges')) {
      breadcrumbs.push({ label: '学院管理', path: '/app/colleges' });
      if (pathname === '/app/colleges/add') {
        breadcrumbs.push({ label: '添加学院', path: '/app/colleges/add' });
      }
    } else if (pathname.startsWith('/app/students')) {
      breadcrumbs.push({ label: '学生管理', path: '/app/students' });
      if (pathname === '/app/students/add') {
        breadcrumbs.push({ label: '添加学生', path: '/app/students/add' });
      }
    } else if (pathname.startsWith('/app/classes')) {
      breadcrumbs.push({ label: '班级管理', path: '/app/classes' });
      if (pathname === '/app/classes/add') {
        breadcrumbs.push({ label: '添加班级', path: '/app/classes/add' });
      }
    } else if (pathname.startsWith('/app/classrooms')) {
      breadcrumbs.push({ label: '教室管理', path: '/app/classrooms' });
      if (pathname === '/app/classrooms/add') {
        breadcrumbs.push({ label: '添加教室', path: '/app/classrooms/add' });
      }
    } else if (pathname.startsWith('/app/grades')) {
      breadcrumbs.push({ label: '成绩管理', path: '/app/grades' });
      if (pathname === '/app/grades/add') {
        breadcrumbs.push({ label: '添加成绩', path: '/app/grades/add' });
      }
    } else if (pathname.startsWith('/app/teachers')) {
      breadcrumbs.push({ label: '教师管理', path: '/app/teachers' });
      if (pathname === '/app/teachers/add') {
        breadcrumbs.push({ label: '添加教师', path: '/app/teachers/add' });
      }
    }

    else if (pathname.startsWith('/app/comprehensive-scores')) {
      breadcrumbs.push({ label: '综合积分管理', path: '/app/comprehensive-scores' });
      if (pathname === '/app/comprehensive-scores/add') {
        breadcrumbs.push({ label: '添加积分', path: '/app/comprehensive-scores/add' });
      }
    } else if (pathname.startsWith('/app/attendance')) {
        breadcrumbs.push({ label: '出勤管理', path: '/app/attendance' });
      } else if (pathname.startsWith('/app/notifications')) {
        breadcrumbs.push({ label: '通知公告', path: '/app/notifications' });
      } else if (pathname.startsWith('/app/counselors')) {
        breadcrumbs.push({ label: '辅导员管理', path: '/app/counselors' });
        if (pathname === '/app/counselors/add') {
          breadcrumbs.push({ label: '添加辅导员', path: '/app/counselors/add' });
        }
      } else if (pathname.startsWith('/app/dormitories')) {
        breadcrumbs.push({ label: '宿舍管理', path: '/app/dormitories' });
        if (pathname === '/app/dormitories/add') {
          breadcrumbs.push({ label: '添加宿舍', path: '/app/dormitories/add' });
        }
      } else if (pathname.startsWith('/app/dormitory-buildings')) {
        breadcrumbs.push({ label: '宿舍楼管理', path: '/app/dormitory-buildings' });
        if (pathname === '/app/dormitory-buildings/add') {
          breadcrumbs.push({ label: '添加宿舍楼', path: '/app/dormitory-buildings/add' });
        }
      } else if (pathname.startsWith('/app/market-departments')) {
        breadcrumbs.push({ label: '市场部管理', path: '/app/market-departments' });
        if (pathname === '/app/market-departments/add') {
          breadcrumbs.push({ label: '添加市场部', path: '/app/market-departments/add' });
        }
      } else if (pathname.startsWith('/app/settings')) {
        breadcrumbs.push({ label: '系统设置', path: '/app/settings' });
      if (pathname === '/app/settings/users') {
        breadcrumbs.push({ label: '用户管理', path: '/app/settings/users' });
      } else if (pathname === '/app/settings/permissions') {
        breadcrumbs.push({ label: '权限管理', path: '/app/settings/permissions' });
      } else if (pathname === '/app/settings/roles') {
        breadcrumbs.push({ label: '角色管理', path: '/app/settings/roles' });
      } else if (pathname === '/app/settings/permission-assignment') {
        breadcrumbs.push({ label: '权限分配', path: '/app/settings/permission-assignment' });
      }
    } else if (pathname === '/audit-logs') {
      breadcrumbs.push({ label: '审计日志', path: '/audit-logs' });
    }
    
    return breadcrumbs;
  };

   // 根据路径渲染不同的页面内容
const renderPageContent = () => {
    if (!isAuthenticated) {
      return (
        <div className="flex items-center justify-center h-full">
          <div className="text-center">
            <Text className="text-xl text-gray-500 mb-4">请先登录</Text>
            <Button variant="primary" onClick={handleLogin}>
              去登录
            </Button>
          </div>
        </div>
      );
    }

      const pathname = location.pathname;
      if (pathname === '/app' || pathname === '/app/dashboard') {
        return <DashboardPage />;
      } else if (pathname.startsWith('/app/colleges')) {
        return <CollegeManagementPage />;
      } else if (pathname.startsWith('/app/students')) {
        return <StudentManagementPage />;
      } else if (pathname.startsWith('/app/classes')) {
        return <ClassManagementPage />;
      } else if (pathname.startsWith('/app/classrooms')) {
        return <ClassroomManagementPage />;
      } else if (pathname.startsWith('/app/grades')) {
        return <GradeManagementPage />;
      } else if (pathname.startsWith('/app/teachers')) {
        return <TeacherManagementPage />;
      } else if (pathname.startsWith('/app/comprehensive-scores')) {
        return <ComprehensiveScoreManagementPage />;
      } else if (pathname.startsWith('/app/attendance')) {
        return <AttendanceManagementPage />;
      } else if (pathname.startsWith('/app/notifications')) {
        return <NotificationManagementPage />;
      } else if (pathname.startsWith('/app/settings/permissions')) {
        return <PermissionManagementPage />;
      } else if (pathname.startsWith('/app/settings/roles')) {
        return <RoleManagementPage />;
      } else if (pathname.startsWith('/app/settings')) {
        return <SystemSettingsPage />;
      } else if (pathname.startsWith('/app/counselors')) {
        return <CounselorManagementPage />;
      } else if (pathname.startsWith('/app/dormitories')) {
        return <DormitoryManagementPage />;
      } else if (pathname.startsWith('/app/dormitory-buildings')) {
        return <DormitoryBuildingManagementPage />;
      } else if (pathname.startsWith('/app/market-departments')) {
        return <MarketDepartmentManagementPage />;
      }

      return <DashboardPage />;
  };
  return (
    <div className="min-h-screen bg-gray-50 flex">
      {/* 会话指示器 */}
      {isAuthenticated && <SessionIndicator />}
      
      {/* 左侧边栏 */}
      {isAuthenticated && (
        <Sidebar 
          isCollapsed={sidebarCollapsed} 
          onToggle={() => setSidebarCollapsed(!sidebarCollapsed)} 
        />
      )}

     {/* 右侧主内容区域 */}
      <div className={`flex-1 flex flex-col transition-all duration-300 ${isAuthenticated ? (sidebarCollapsed ? 'ml-16' : 'ml-72') : ''}`}>
        {/* 顶部工具栏 */}
        <div className="bg-white shadow-sm border-b px-6 py-4">
          <div className="flex items-center justify-between">
            <div>
              <Text className="text-lg font-semibold text-gray-900">
                {location.pathname === '/app' || location.pathname === '/app/dashboard' ? '仪表板' :
                 location.pathname.startsWith('/app/classrooms') ? '教室管理' :
                 location.pathname.startsWith('/app/students') ? '学生管理' :
                 location.pathname.startsWith('/app/colleges') ? '学院管理' :
                 location.pathname.startsWith('/app/classes') ? '班级管理' :

                 location.pathname.startsWith('/app/grades') ? '成绩管理' :
                 location.pathname.startsWith('/app/attendance') ? '出勤管理' :
                 location.pathname.startsWith('/app/teachers') ? '教师管理' :
               
                 location.pathname.startsWith('/app/comprehensive-scores') ? '综合积分管理' :
                 location.pathname.startsWith('/app/notifications') ? '通知公告' :
                 location.pathname.startsWith('/app/settings/users') ? '用户管理' :
                 location.pathname.startsWith('/app/settings/permissions') ? '权限管理' :
                 location.pathname.startsWith('/app/settings/roles') ? '角色管理' :
                 location.pathname.startsWith('/app/settings/permission-assignment') ? '权限分配' :
                 location.pathname === '/audit-logs' ? '审计日志' :
                 location.pathname.startsWith('/app/counselors') ? '辅导员管理' :
                 location.pathname.startsWith('/app/dormitories') ? '宿舍管理' :
                 location.pathname.startsWith('/app/dormitory-buildings') ? '宿舍楼管理' :
                 location.pathname.startsWith('/app/market-departments') ? '市场部管理' :
                 location.pathname.startsWith('/app/settings') ? '系统设置' : '学生管理系统'}
              </Text>
            </div>
            
            {/* 主题和语言切换按钮（勿动） */}
            <div className="flex items-center space-x-2">
              <Button variant="outline" size="sm" onClick={handleTheme}>
                {Theme === 'light' ? '🌙' : '☀️'}
            </Button>
              <Button variant="outline" size="sm" onClick={handleLang}>
                {local === 'zh' ? 'EN' : '中'}
                  </Button>
            </div>
          </div>
        </div>

        {/* 面包屑导航 */}
        {isAuthenticated && (
          <div className="bg-white border-b px-6 py-2 flex items-center text-sm">
            {getBreadcrumbData().map((crumb, index, array) => (
              <React.Fragment key={crumb.path}>
                <a 
                  href={crumb.path} 
                  onClick={(e) => {
                    e.preventDefault();
                    navigate(crumb.path);
                  }}
                  className={`cursor-pointer ${index === array.length - 1 ? 'text-gray-900 font-medium' : 'text-blue-600 hover:text-blue-800'}`}
                >
                  {crumb.label}
                </a>
                {index < array.length - 1 && (
                  <span className="mx-2 text-gray-400">/</span>
                )}
              </React.Fragment>
            ))}
          </div>
        )}

        {/* 页面内容 */}
        <div className="flex-1 overflow-auto">
          {renderPageContent()}
            </div>
          </div>
    </div>
  );
}

export default App;